#include <sstream>
#include "scr_resource_manager.h"
#include "scr_math.h"
#include "scr_texture.h"
#include "scr_font.h"
#include "scr_music.h"
#include "scr_sound.h"

SCRResourceManager::SCRResourceManager()
{
}

SCRResourceManager::~SCRResourceManager()
{
}

SCRTexturePtr SCRResourceManager::GetTexture(const std::string& Filename, const bool& HasAlpha)
{
	const unsigned int HashFromName = SCRMath::GetHash(Filename);
	SCRTexturePtrMap::const_iterator Iterator = m_TextureMap.find(HashFromName);
	if (Iterator != m_TextureMap.end())
	{
		return Iterator->second;
	}
	else
	{
		SCRTexturePtr TexturePtr(new SCRTexture(Filename, HasAlpha));
		if (TexturePtr->IsValid())
		{
			m_TextureMap[HashFromName] = TexturePtr;
		}
		else
		{
			TexturePtr.reset();
		}

		return TexturePtr;
	}
}

SCRFontPtr SCRResourceManager::GetFont(const std::string& Filename, const int& Size)
{
	std::ostringstream FilenameSize;
	FilenameSize << Filename << Size;
	const unsigned int HashFromName = SCRMath::GetHash(FilenameSize.str());
	SCRFontPtrMap::const_iterator Iterator = m_FontMap.find(HashFromName);
	if (Iterator != m_FontMap.end())
	{
		return Iterator->second;
	}
	else
	{
		SCRFontPtr FontPtr(new SCRFont(Filename, Size));
		if (FontPtr->IsValid())
		{
			m_FontMap[HashFromName] = FontPtr;
		}
		else
		{
			FontPtr.reset();
		}

		return FontPtr;
	}
}

SCRMusicPtr SCRResourceManager::GetMusic(const std::string& Filename)
{
	const unsigned int HashFromName = SCRMath::GetHash(Filename);
	SCRMusicPtrMap::const_iterator Iterator = m_MusicMap.find(HashFromName);
	if (Iterator != m_MusicMap.end())
	{
		return Iterator->second;
	}
	else
	{
		SCRMusicPtr MusicPtr(new SCRMusic(Filename));
		if (MusicPtr->IsValid())
		{
			m_MusicMap[HashFromName] = MusicPtr;
		}
		else
		{
			MusicPtr.reset();
		}

		return MusicPtr;
	}
}

SCRSoundPtr SCRResourceManager::GetSound(const std::string& Filename)
{
	const unsigned int HashFromName = SCRMath::GetHash(Filename);
	SCRSoundPtrMap::const_iterator Iterator = m_SoundMap.find(HashFromName);
	if (Iterator != m_SoundMap.end())
	{
		return Iterator->second;
	}
	else
	{
		SCRSoundPtr SoundPtr(new SCRSound(Filename));
		if (SoundPtr->IsValid())
		{
			m_SoundMap[HashFromName] = SoundPtr;
		}
		else
		{
			SoundPtr.reset();
		}

		return SoundPtr;
	}
}